package com.arthur.system.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.arthur.common.domain.ResponseBo;

/**
 * 文件上传
 * 
 * @author Fly
 *
 */
@RestController
public class UploadController {

	/**
	 * 文件上传根目录(在Spring的application.yml的配置文件中配置):<br>
	 * web: upload-path: （jar包所在目录）/resources/static/
	 */
	@Value("${web.upload-path}")
	private String webUploadPath;
	
	private final ResourceLoader resourceLoader;  
	  
    @Autowired  
    public UploadController(ResourceLoader resourceLoader) {  
        this.resourceLoader = resourceLoader;  
    }

	/**
	 * ResultVo是一个对象，包含： private int errorCode; private String errorMsg; private
	 * Integer total; private Object data;
	 */

	/**
	 * 基于用户标识的头像上传
	 * 
	 * @param file
	 *            图片
	 * @param userId
	 *            用户标识
	 * @return
	 */
	@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseBo fileUpload(@RequestParam("file") MultipartFile file) {
		if(StringUtils.isBlank(webUploadPath)){
			webUploadPath = System.getProperty("user.dir") + "/upload/";
		}
		
		if (!file.isEmpty()) {
			if (file.getContentType().contains("image")) {
				try {
					String temp = File.separator + "img" + File.separator;
					// 获取图片的文件名
					String fileName = file.getOriginalFilename();
					// 获取图片的扩展名
					String extensionName = StringUtils.substringAfter(fileName, ".");
					// 新的图片文件名 = 获取时间戳+"."图片扩展名
					String newFileName = String.valueOf(System.currentTimeMillis()) + "." + extensionName;
					// 数据库保存的目录
					String datdDirectory = temp;
					// 文件路径
					String filePath = webUploadPath.concat(datdDirectory);

					File dest = new File(filePath, newFileName);
					if (!dest.getParentFile().exists()) {
						dest.getParentFile().mkdirs();
					}
					// 上传到指定目录
					file.transferTo(dest);

					// 将图片流转换进行BASE64加码
					// BASE64Encoder encoder = new BASE64Encoder();
					// String data = encoder.encode(file.getBytes());

					// 将反斜杠转换为正斜杠
					String data = datdDirectory.replaceAll("\\\\", "/") + newFileName;
					return ResponseBo.ok(data).put("filename", fileName);
				} catch (IOException e) {
					return ResponseBo.error(e.getMessage());
				}
			} else {
				return ResponseBo.error("上传的文件不是图片类型，请重新上传!");
			}
		} else {
			return ResponseBo.error("上传失败，请选择要上传的图片!");
		}
	}
	
	

	@RequestMapping(method = RequestMethod.GET, value = "img/{filename:.+}")  
    @ResponseBody  
    public ResponseEntity<?> getFile(@PathVariable String filename) {
		if(StringUtils.isBlank(webUploadPath)){
			webUploadPath = System.getProperty("user.dir") + "/upload/";
		}
        try {
        	String datdDirectory = "img" + File.separator;
            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(webUploadPath+datdDirectory, filename).toString()));  
        } catch (Exception e) {  
            return ResponseEntity.notFound().build();  
        }  
    }

}